package com.hzit.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzit.entity.LoginUser;
import com.hzit.entity.User;
import com.hzit.mapper.UserMapper;
import com.hzit.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wf
 * @since 2024-08-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

	/**
	 * 验证是否登录，登录就返回用户
	 * @param username
	 * @param password
	 * @return
	 */
	@Override
	public LoginUser findById(String username, String password) {
		LoginUser loginUser = new LoginUser();
		// 1.1 根据用户名得到用户对象
		User user = this.getOne(new QueryWrapper<User>().eq("username", username));
		// 1.2 将传入的密码进行md5加密再与数据库中的密码进行比较，如果相等，证明有此用户
		if(!Objects.isNull(user)){
			if(StrUtil.isNotBlank(password)) {
				String pwd = SecureUtil.md5(password);
				if(pwd.equals(user.getPassword())){
					loginUser.setUser(user);
					loginUser.setUserId(user.getId());
					//查询出登录用户的权限串列表
					List<String> permssions = this.baseMapper.findPermissionByUsername(username);
					loginUser.setPermissions(permssions);
					return loginUser;
				}
			}
		}

		return null;
	}
}
